import {
    useEffect,
    useState,
    forwardRef,
    useImperativeHandle,
    useMemo,
} from "react";
import {
    useAccount,
    useBalance,
    useReadContracts,
    useWriteContract,
    useWaitForTransactionReceipt,
} from "wagmi";
import {
    contractAddress,
    miningContract,
    tokenContract,
} from "../../provider/Contract";
import Big from "big.js";

export interface ReceiveComponentType {
    refetchAll: () => void;
}

const Receive = forwardRef<ReceiveComponentType>((_, ref) => {
    const { address } = useAccount();
    const [error, setError] = useState<string | null>(null);
    const [txStatus, setTxStatus] = useState<string | null>(null);
    const [tokenBalance, setTokenBalance] = useState("0");
    const [tokenAllowance, setTokenAllowance] = useState("0");
    const [receiveAmount, setReceiveAmount] = useState<string>("0.001");
    const [approveAmount, setApproveAmount] = useState<string>("20");

    const multiplier = useMemo(() => new Big(10).pow(18), []);
    const {
        writeContract,
        data: txHash,
        isPending,
        error: writeError,
    } = useWriteContract();
    const {
        isSuccess: isTxConfirmed,
        isLoading: isTxLoading,
        isError: isTxError,
        error: txError,
    } = useWaitForTransactionReceipt({
        hash: txHash,
        query: {
            enabled: !!txHash,
        },
    });

    const {
        data: result,
        isSuccess,
        refetch,
    } = useReadContracts({
        contracts: [
            {
                ...tokenContract,
                functionName: "balanceOf",
                args: [address],
            },
            {
                ...tokenContract,
                functionName: "allowance",
                args: [address, contractAddress],
            },
        ],
        query: {
            enabled: !!address,
        },
    });

    useEffect(() => {
        if (result && isSuccess && result[0].result && result[1].result) {
            const balance = new Big(result[0].result.toString())
                .div(multiplier)
                .toString();
            const allowance = new Big(result[1].result.toString())
                .div(multiplier)
                .toString();
            setTokenBalance(balance);
            setTokenAllowance(allowance);
        }
    }, [result, isSuccess, multiplier]);

    useEffect(() => {
        if (isTxConfirmed) {
            setTxStatus("交易确认成功！");
            refetch();
        }
        if (isTxError && txError) {
            setError("交易失败：" + txError.message);
        }
        if (writeError) {
            setError("交易失败：" + writeError.message);
        }
    }, [isTxConfirmed, isTxError, txError, writeError, refetch]);

    const { data: mainBalance, refetch: mainBalanceRefetch } = useBalance({
        address,
        query: {
            enabled: !!address,
        },
    });

    const receiveToken = () => {
        try {
            if (!address) {
                throw new Error("请先连接钱包");
            }
            if (
                !receiveAmount ||
                isNaN(Number(receiveAmount)) ||
                Number(receiveAmount) <= 0
            ) {
                throw new Error("无效的领取金额");
            }
            const val = new Big(receiveAmount).times(multiplier).toString();
            writeContract({
                ...miningContract,
                functionName: "receiveToken",
                args: [val],
                gas: 200000n,
            });
        } catch (error) {
            setError("领取失败：" + (error as Error).message);
        }
    };

    const approve = () => {
        try {
            if (!address) {
                throw new Error("请先连接钱包");
            }
            if (
                !approveAmount ||
                isNaN(Number(approveAmount)) ||
                Number(approveAmount) <= 0
            ) {
                throw new Error("无效的授权金额");
            }
            const val = new Big(approveAmount).times(multiplier).toString();
            writeContract({
                ...tokenContract,
                functionName: "approve",
                args: [contractAddress, val],
                gas: 100000n,
            });
        } catch (error) {
            setError("授权失败：" + (error as Error).message);
        }
    };

    const refetchAll = () => {
        refetch();
        mainBalanceRefetch();
    };

    useImperativeHandle(ref, () => ({
        refetchAll,
    }));

    return (
        <div
            style={{
                border: "1px solid #e0e0e0",
                borderRadius: "8px",
                padding: "16px",
                margin: "16px 0",
                backgroundColor: "#fff",
                boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
                maxWidth: "400px",
                fontFamily: "Arial, sans-serif",
            }}
        >
            {/* 状态提示 */}
            {error && (
                <div
                    style={{
                        color: "#d32f2f",
                        backgroundColor: "#ffebee",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    {error}
                </div>
            )}
            {txStatus && (
                <div
                    style={{
                        color: "#2e7d32",
                        backgroundColor: "#e8f5e9",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    {txStatus}
                </div>
            )}
            {isTxLoading && (
                <div
                    style={{
                        color: "#0288d1",
                        backgroundColor: "#e3f2fd",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    交易处理中...
                </div>
            )}
            {isPending && (
                <div
                    style={{
                        color: "#0288d1",
                        backgroundColor: "#e3f2fd",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    等待钱包确认...
                </div>
            )}
            {txHash && (
                <div
                    style={{
                        color: "#424242",
                        fontSize: "12px",
                        wordBreak: "break-all",
                        marginBottom: "12px",
                    }}
                >
                    交易哈希: {txHash}
                </div>
            )}

            {/* 余额和授权信息 */}
            <div
                style={{
                    display: "grid",
                    gridTemplateColumns: "1fr 2fr",
                    gap: "8px",
                    marginBottom: "16px",
                }}
            >
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    代币余额:
                </span>
                <span>{tokenBalance}</span>
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    授权额度:
                </span>
                <span>{tokenAllowance}</span>
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    主链余额:
                </span>
                <span>
                    {mainBalance
                        ? new Big(mainBalance.value.toString())
                              .div(multiplier)
                              .toString()
                        : "加载中..."}
                </span>
            </div>

            {/* 领取代币 */}
            <div style={{ marginBottom: "16px" }}>
                <input
                    type="number"
                    value={receiveAmount}
                    onChange={(e) => setReceiveAmount(e.target.value)}
                    placeholder="输入领取金额"
                    disabled={!address || isPending || isTxLoading}
                    style={{
                        padding: "8px",
                        border: "1px solid #e0e0e0",
                        borderRadius: "4px",
                        fontSize: "14px",
                        width: "100%",
                        outline: "none",
                        transition: "border-color 0.2s",
                        marginBottom: "8px",
                    }}
                    onFocus={(e) => (e.target.style.borderColor = "#1976d2")}
                    onBlur={(e) => (e.target.style.borderColor = "#e0e0e0")}
                />
                <button
                    disabled={!address || isPending || isTxLoading}
                    onClick={receiveToken}
                    style={{
                        padding: "8px 16px",
                        backgroundColor:
                            address && !isPending && !isTxLoading
                                ? "#1976d2"
                                : "#bdbdbd",
                        color: "#fff",
                        border: "none",
                        borderRadius: "4px",
                        cursor:
                            address && !isPending && !isTxLoading
                                ? "pointer"
                                : "not-allowed",
                        fontSize: "14px",
                        transition: "background-color 0.2s",
                        width: "100%",
                    }}
                    onMouseOver={(e) =>
                        address && !isPending && !isTxLoading
                            ? (e.currentTarget.style.backgroundColor =
                                  "#1565c0")
                            : null
                    }
                    onMouseOut={(e) =>
                        address && !isPending && !isTxLoading
                            ? (e.currentTarget.style.backgroundColor =
                                  "#1976d2")
                            : null
                    }
                >
                    {address ? "领取代币" : "连接钱包以领取"}
                </button>
            </div>

            {/* 授权 */}
            <div>
                <input
                    type="number"
                    value={approveAmount}
                    onChange={(e) => setApproveAmount(e.target.value)}
                    placeholder="输入授权金额"
                    disabled={!address || isPending || isTxLoading}
                    style={{
                        padding: "8px",
                        border: "1px solid #e0e0e0",
                        borderRadius: "4px",
                        fontSize: "14px",
                        width: "100%",
                        outline: "none",
                        transition: "border-color 0.2s",
                        marginBottom: "8px",
                    }}
                    onFocus={(e) => (e.target.style.borderColor = "#1976d2")}
                    onBlur={(e) => (e.target.style.borderColor = "#e0e0e0")}
                />
                <button
                    disabled={!address || isPending || isTxLoading}
                    onClick={approve}
                    style={{
                        padding: "8px 16px",
                        backgroundColor:
                            address && !isPending && !isTxLoading
                                ? "#1976d2"
                                : "#bdbdbd",
                        color: "#fff",
                        border: "none",
                        borderRadius: "4px",
                        cursor:
                            address && !isPending && !isTxLoading
                                ? "pointer"
                                : "not-allowed",
                        fontSize: "14px",
                        transition: "background-color 0.2s",
                        width: "100%",
                    }}
                    onMouseOver={(e) =>
                        address && !isPending && !isTxLoading
                            ? (e.currentTarget.style.backgroundColor =
                                  "#1565c0")
                            : null
                    }
                    onMouseOut={(e) =>
                        address && !isPending && !isTxLoading
                            ? (e.currentTarget.style.backgroundColor =
                                  "#1976d2")
                            : null
                    }
                >
                    {address ? "授权" : "连接钱包以授权"}
                </button>
            </div>
        </div>
    );
});

export default Receive;
